package drp.snowbell.cfg;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.apache.log4j.Logger;

import drp.snowbell.exception.CatchException;
import drp.snowbell.util.cfg.XmlConfigFactory;
import drp.snowbell.util.file.FileUtility;


/**
 * 系统配置管理器
 * 
 * @author wuhj
 * 
 */
public class Config {

	public final static String CORE_MODULE_NAME = "system";

	/**
	 * 加载主要配置
	 */
	private static SystemConfig systemConfig;

	private static Logger logger = Logger.getLogger(Config.class);

	/**
	 * 获取模块配置
	 * 
	 * @param moduleName
	 *            模块名称
	 * @return
	 */
	public static ModuleConfig getModuleConfig(String moduleName) {

		ModuleConfig ret = null;
		String path = Location.MODULES_ROOT + moduleName + File.separator + Location.MODULE_CONFIG_FILE_NAME;
		try {
			ret = (ModuleConfig) XmlConfigFactory.get().load(path);
		} catch (IOException e) {
			CatchException.take(e);
		}

		return ret;
	}

	/**
	 * 获取某个模块的所有实体配置
	 * 
	 * @param moduleName
	 * @return
	 */
	public static Collection<EntityConfig> getEntityConfigList(String moduleName) {
		Collection<EntityConfig> ret = new ArrayList<EntityConfig>();
		String path = Location.getEntityConfigPath(moduleName);
		File file = FileUtility.getFile(path);
		File[] cfgList = file.listFiles(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				return name.endsWith(Location.CONFIG_FILE_EXT);
			}
		});
		for (File fileCfg : cfgList) {
			EntityConfig ec = null;
			try {
				ec = (EntityConfig) XmlConfigFactory.get().load(fileCfg);
				if (ec != null) {
					ret.add(ec);
				}
			} catch (IOException e) {
				CatchException.take(e);
			}
			if (ec == null) {
				logger.error("can't initialize core entity config:" + fileCfg.getPath());
			}
		}

		return ret;
	}

	/**
	 * 获取系统配置
	 * 
	 * @return
	 */
	public static SystemConfig get() {
		if (systemConfig == null) {
			try {
				systemConfig = (SystemConfig) XmlConfigFactory.get().load(Location.SYSTEM_CONFIG_PATH);
			} catch (IOException e) {
				CatchException.take(e);
			}
		}
		return systemConfig;
	}
}
